import React, { Component } from 'react'
import {
  Form,
  Input,
  Tree
} from 'antd'
import PropTypes from 'prop-types'
import menuList from '../../config/menuConfig'

/**
 * 添加分类组件
 */

const Item = Form.Item
const { TreeNode } = Tree

export default class AuthForm extends Component {

  
  static propTypes = {
    role: PropTypes.object
  }

  /**
   * 根据传入的角色的menus生成初始状态
   */
  constructor(props) {
    super(props)
    const {menus} = this.props.role
    this.state = {
      checkedKeys: menus
    }
  }

  /**
   * 为父组件提交获取最新menus数据的方法
   */
  getMenus = () =>this.state.checkedKeys

  /**
   * 获取角色权限菜单
   */
  getTreeNodes = (menuList) => {
    return menuList.reduce((pre,item) => {
      pre.push(
        <TreeNode title={item.title} key={item.key}>
          {item.children ? this.getTreeNodes(item.children) : null}
        </TreeNode>
      )
      return pre
    },[])
  }

  /**
   * 选中某个node时回调
   */
  onCheck = checkedKeys => {
    console.log('onCheck', checkedKeys);
    this.setState({ checkedKeys });
  };

  UNSAFE_componentWillMount() {
    this.treeNodes = this.getTreeNodes(menuList)
  }


  /**
   * 根据新传入的role来更新checkedKeys状态
   * 当组件接收到新的属性是自动调用
   */
  UNSAFE_componentWillReceiveProps(nextProps) {
    const menus = nextProps.role.menus
    this.setState({
      checkedKeys: menus
    })
  }

  render() {
    const {role} = this.props
    const {checkedKeys} = this.state
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 16 },
    }
    return (
      <Form>
        <Item label='角色名称' {...formItemLayout}>
          <Input value={role.name} disabled></Input>
        </Item>
        <Tree
          checkable
          defaultExpandAll={true}
          checkedKeys={checkedKeys}
          onCheck={this.onCheck}
        >
        <TreeNode title="平台权限" key="all">
          {this.treeNodes}
        </TreeNode>
      </Tree>
      </Form>
    )
  }
}
